﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Zhy.HelpClassLibrary.Utility.XmlHelper
{
    public class XmlHelper
    {
        /// <summary>
        /// 将xml文件序列化成实体
        /// </summary>
        /// <typeparam name="T">要序列化的类型</typeparam>
        /// <param name="fileName">xml文档路径</param>
        /// <returns></returns>
        public static T XmlToModel<T>(string fileName)
           where T : new()
        {
            using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
            {
                XmlSerializer xmlFormat = new XmlSerializer(typeof(T));//创建XML序列化器，需要指定对象的类型
                //使用XML反序列化对象
                fStream.Position = 0;//重置流位置
                T pList = (T)xmlFormat.Deserialize(fStream);
                return pList;
            }
        }

        /// <summary>
        /// 将实体序列化成xml保存
        /// </summary>
        /// <typeparam name="T">要序列化的类型</typeparam>
        /// <param name="fileName">xml文档路径</param>
        /// <returns></returns>
        public static bool XmlToSave<T>(string fileName, T pList)
           where T : new()
        {
            //使用XML序列化对象 
            using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
            {
                XmlSerializer xmlFormat = new XmlSerializer(typeof(T));//创建XML序列化器，需要指定对象的类型
                xmlFormat.Serialize(fStream, pList);
                return true;
            }
        }
    }
}
